package com.qf.shopping.servlet.frontController;

import com.alibaba.fastjson.JSON;
import com.qf.shopping.common.Constants;
import com.qf.shopping.common.DisatpcherServlet;
import com.qf.shopping.entity.Product;
import com.qf.shopping.entity.ShoppingCart;
import com.qf.shopping.entity.User;
import com.qf.shopping.service.ICartService;
import com.qf.shopping.service.IProductService;
import com.qf.shopping.service.impl.CartServiceImpl;
import com.qf.shopping.service.impl.ProductServiceImpl;
import com.qf.shopping.utils.ResultResponse;
import sun.rmi.runtime.NewThreadAction;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.PrintConversionEvent;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**购物车模块
 * @author 三旬
 * @version 1.0  2022/9/22
 */
@WebServlet("/ShoppingCartController/*")
public class ShoppingCartController extends DisatpcherServlet {

    private ICartService cartService = new CartServiceImpl();
    private IProductService productServicet = new ProductServiceImpl();

    /**
     * 添加商品到购物车
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    public String addProductToCart(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //接收用户加入购物车的商品信息
        String json = request.getReader().readLine();
        //封装
        ShoppingCart cart = JSON.parseObject(json,ShoppingCart.class);
        //从session中取出用户的id
        User user = (User) request.getSession().getAttribute("user");
        cart.setUid(user.getId());
        //调用业务层处理
        Boolean result = cartService.addToMyCart(cart);
        if (result) {
            return Constants.JSON+":"+ ResultResponse.success("加入购物车成功！");
        }
        return Constants.JSON+":"+ResultResponse.Error("加入购物车失败!");
    }

    /**
     * 查看我的购物车
     * @param request
     * @param response
     */
    public String myCart(HttpServletRequest request,HttpServletResponse response){
        //获得登录人的id
        User user = (User) request.getSession().getAttribute("user");
        Integer uid = user.getId();
        //调用业务层获取购物车商品信息
        List<ShoppingCart> cart = cartService.getMyCart(uid);
        //循环遍历查询购物车中的每个商品详情
        //所有商品的总金额
       BigDecimal sumPrice = new BigDecimal(0.0);
        for (ShoppingCart c : cart) {
            Product p = c.getProduct();
            //每种商品的金额
            BigDecimal oneProductPrice = p.getPrice().multiply(BigDecimal.valueOf(c.getNums()));
            sumPrice = sumPrice.add(oneProductPrice);
        }
        //将购物车信息和商品总金额放到request中
        request.setAttribute("cart",cart);
        request.setAttribute("sumPrice",sumPrice);
        //转发跳转到购物车页面
        return Constants.FORWARD+":"+"shopcat.jsp";
    }

    /**
     * 移除购物车里的一类商品
     * @param request
     * @param response
     * @return
     */
    public String deleteOneProduct(HttpServletRequest request,HttpServletResponse response){
        //获取商品的id、用户的id
        Integer pid = Integer.valueOf(request.getParameter("pid"));
        //从session中获取用户的id
        Integer uid = ((User)request.getSession().getAttribute("user")).getId();
        //删除购物车中指定的商品
        boolean result = cartService.deleteByPidAndUid(pid,uid);
        if (result) {
            return Constants.REDIRECT+":"+"ShoppingCartController/myCart";
        }
        return Constants.SCRIPT+":"+"删除失败！";
    }

    /**
     * 修改购物车商品的数量（后台修改，前台刷新）
     * @param request
     * @param response
     * @return
     */
    public String updateMyProductNums(HttpServletRequest request,HttpServletResponse response){
        //接收前端传来的参数（修改的商品pid和状态flag）
        Integer pid = Integer.valueOf(request.getParameter("id"));
        Integer flag = Integer.valueOf(request.getParameter("flag"));
        //从session 中获得用户的uid
        Integer uid = ((User) request.getSession().getAttribute("user")).getId();
        //调用业务层处理
        Map<String,Object> map = cartService.updateMyProductNums(pid,uid,flag);

        String json = JSON.toJSONString(map);
        return Constants.JSON+":"+json;
    }

    /**
     * 获得购物车商品的数量（不同的商品数量）
     * @param request
     * @param response
     * @return
     */
    public String getCartProductNumsByUid(HttpServletRequest request,HttpServletResponse response){
        //先获得用户的id
        User user = (User) request.getSession().getAttribute("user");
        if(user != null){
            Integer uid = user.getId();
            Integer result = cartService.getCartProductNumsByUid(uid);
            return  Constants.JSON+":"+ResultResponse.success(result);
        }
        return Constants.JSON+":"+ResultResponse.Error(" ");
    }
    public String adeleteOneProduct(HttpServletRequest request,HttpServletResponse response){
        return null;
    }

}
